package g.beny.framework.web;

import g.beny.framework.exception.BenyException;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.json.JsonFormat;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.RequestPath;
import org.nutz.mvc.View;

/**
 * 扩展的自定错误视图--系统级别异常
 * 
 * @ClassName FailView
 * @Description TODO
 * @author gson
 * @date 2012-7-29 下午3:20:11
 * 
 */
public class FailView implements View {

	@Override
	public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) {
		try {
			String basePath = req.getScheme() + "://" + req.getServerName() + (req.getServerPort() == 80 ? "" : ":" + req.getServerPort()) + req.getContextPath();
			RequestPath rp = Mvcs.getRequestPathObject(req);
			String path = basePath+rp.getUrl();
			
			BenyException ex = (BenyException) obj;
			resp.setStatus(ex.getCode());
			String requestType = req.getHeader("X-Requested-With");
			// 判断是否是ajax请求，如果是ajax请求。否则进行界面跳转
			if (requestType != null && requestType.equals("XMLHttpRequest")) {
				HashMap<String, Object> result = new HashMap<String, Object>();
				result.put("type", ex.getType());
				result.put("path", path);
				result.put("message", ex.getMsg());
				result.put("stackTrace", ex.getStringStackTrace());
				Mvcs.write(resp, result, new JsonFormat(false));
			} else {
				req.setAttribute("type", ex.getType());
				req.setAttribute("path", path);
				req.setAttribute("message", ex.getMsg());
				req.setAttribute("stackTrace", ex.getStringStackTrace());
				RequestDispatcher rd = req.getRequestDispatcher("/WEB-INF/page/fail.jsp");
				rd.forward(req, resp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
